<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@page contentType="text/html" pageEncoding="UTF-8" %>
<c:if test="${empty sessionScope.user}">
    <c:redirect url="/login"/>
</c:if>
<c:if test="${sessionScope.role==2}">
    <script>
        alert("你没有权限访问该页面")
    </script>
</c:if>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>新闻管理 - 新闻管理系统</title>
    <link rel="stylesheet" href="../../resources/css/admin-style.css">
    <style>
        #news-text {
            width: 100%;
            padding: 10px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
            resize: vertical;
        }
    </style>
</head>
<body class="admin-body">
<!-- 侧边栏 -->
<aside class="admin-sidebar">
    <div class="sidebar-header">
        <h2>新闻管理系统</h2>
    </div>
    <nav class="sidebar-nav">
        <a href="<c:url value="/dashboard"/>" class="nav-item">仪表盘</a>
        <a href="<c:url value="/list/news"/>" class="nav-item active">新闻管理</a>
        <a href="<c:url value="/list/category"/>" class="nav-item">类型管理</a>
        <c:if test="${sessionScope.role!=3}">
            <a href="<c:url value="/list/user"/>" class="nav-item">用户管理</a>
        </c:if>
        <a href="<c:url value="/list/comm"/>" class="nav-item">评论管理</a>
        <a href="<c:url value="/logout"/>" class="nav-item logout-item">退出登录</a>
    </nav>
</aside>

<!-- 主内容区 -->
<main class="admin-main">
    <header class="admin-header">
        <h1>新闻管理</h1>
        <button id="add-news-btn" class="add-btn" onclick="openAddModal()">+ 添加新闻</button>
    </header>

    <!-- 搜索与筛选 -->
    <div class="news-filter-bar">
        <div class="search-group">
            <input type="text" id="news-search" placeholder="搜索新闻标题...">
            <select id="type-select">
                <!-- JS动态加载分类 -->
                <option value="">全部分类</option>
            </select>
            <button id="search-btn" class="search-btn" onclick="search()">搜索</button>
        </div>
    </div>

    <!-- 新闻表格 -->
    <table class="news-table" id="news-list-table">
        <thead>
        <tr>
            <th>ID</th>
            <th>标题</th>
            <th>分类</th>
            <th>发布时间</th>
            <th>作者</th>
            <th>状态</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody>
        <!-- JS动态渲染 -->
        <c:forEach items="${newsList}" var="item" varStatus="status">
            <tr>
                <td>${newsList.indexOf(item)+1}</td>
                <td>${item.title}</td>
                <td>${item.category}</td>
                <td>${item.air_time}</td>
                <td>${item.author}</td>
                <td><c:if test="${item.status == 1}"><span style="color: #2ecc71">已发布</span></c:if><c:if
                        test="${item.status != 1}"><span style="color:#f39c12">草稿</span></c:if></td>
                <td>
                    <button class="edit-btn" onclick="openAddModal('${item.id}')">编辑</button>
                    <button class="delete-btn" onclick="deleteNews('${item.id}')">删除</button>
                </td>
            </tr>
        </c:forEach>
        </tbody>
    </table>

    <!-- 添加/编辑新闻模态框（默认隐藏） -->
    <div id="news-modal" class="modal hidden">
        <div class="modal-content">
            <div class="modal-header">
                <h3 id="modal-title">添加新闻</h3>
                <span id="close-modal" class="close-btn" onclick="closeModal()">&times;</span>
            </div>
            <div id="news-form">
                <input type="hidden" id="news-id"> <!-- 编辑时存储新闻ID -->
                <div class="form-group">
                    <label for="news-title">新闻标题 <span class="required">*</span></label>
                    <input type="text" id="news-title" required>
                </div>
                <div class="form-group">
                    <label for="news-type">新闻分类 <span class="required">*</span></label>
                    <select id="news-type" required>
                        <option>--选择分类--</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="news-author">作者</label>
                    <input type="text" id="news-author" value="<%=session.getAttribute("user")%>" readonly>
                </div>
                <div class="form-group">
                    <label for="news-image">新闻图片</label>
                    <input type="text" id="news-image" placeholder="输入图片URL">
                </div>
                <div class="form-group">
                    <label for="news-content">新闻简介 <span class="required">*</span></label>
                    <textarea id="news-content" rows="8" required></textarea>
                </div>
                <div class="form-group">
                    <label for="news-text">新闻内容 <span class="required">*</span></label>
                    <textarea id="news-text" rows="8" required></textarea>
                </div>
                <div class="form-group">
                    <label for="news-status">发布状态 <span class="required">*</span></label>
                    <select id="news-status" required>
                        <option value="1">已发布</option>
                        <option value="2">草稿</option>
                    </select>
                </div>
                <div class="modal-footer">
                    <button class="save-btn" id="btn-save">保存</button>
                    <button type="button" id="cancel-btn" class="cancel-btn" onclick="closeModal()">取消</button>
                </div>
            </
            >
        </div>
    </div>
</main>
<script src="../../resources/js/jquery-3.7.1.min.js"></script>
<script>
    function deleteNews(id) {
        if (id === undefined) {
            return;
        }
        console.log(id);
        if (confirm("你确定要删除此新闻吗？")) {
            $(document).ready(function () {
                $.ajax({
                    url: "/list/del/news/" + id,
                    method: 'POST',
                    success: function (data) {
                        if (data === 0) {
                            alert("新闻正在发布中！删除失败！");
                            location.reload();
                            return;
                        }
                        alert("已经删除");
                        location.reload();
                    },
                    error: function () {
                        console.error("出错了！");
                    }
                });
            });
        }
    }

    $(document).ready(function () {
        $.ajax({
            method: 'GET',
            url: '/list/get/category',
            success: function (data) {
                var htm = '';
                for (var i = 0; i < data.length; i++) {
                    htm += "<option value='" + data[i].name + "'>" + data[i].name + "</option>";
                }
                console.log(htm)
                $("#news-type option").after($(htm));
                $("#type-select option").after($(htm));
            }
        });
    });

    function openAddModal(id) {
        if (id != null) {
            $.ajax({
                url: '/list/get/news?id=' + id,
                method: 'GET',
                success: function (data) {
                    console.log(data)
                    document.getElementById('modal-title').textContent = '编辑新闻';
                    document.getElementById('news-id').value = data[0].id;
                    document.getElementById('news-title').value = data[0].title;
                    document.querySelector('#news-type').value = data[0].category;
                    document.getElementById('news-author').value = data[0].author;
                    document.getElementById('news-image').value = data[0].cover || '';
                    document.getElementById('news-content').value = data[0].content;
                    document.getElementById('news-text').value = data[0].text;
                    document.querySelector('#news-status').value = data[0].status;
                    document.getElementById('news-modal').classList.remove('hidden');
                }
            })
            document.getElementById('btn-save').onclick = function () {
                $.ajax({
                    url: '/list/edit/news/',
                    method: 'POST',
                    contentType: 'application/json',
                    headers: {
                        'X-Custom-Header': 'value'
                    },
                    data: JSON.stringify({
                        cover: document.querySelector('#news-image').value,
                        title: document.getElementById('news-title').value,
                        content: document.getElementById('news-content').value,
                        text: document.getElementById('news-text').value,
                        status: document.querySelector('#news-status option:checked').value,
                        category: document.querySelector('#news-type option:checked').value,
                        author: document.getElementById('news-author').value,
                        id: document.getElementById('news-id').value
                    }),
                    success: function () {
                        alert("修改成功！");
                        location.reload();
                    },
                    error: function () {
                        alert("出错了！");
                        location.reload();
                    }
                });
            }
            return;
        }
        document.getElementById('modal-title').textContent = '编辑新闻';
        document.getElementById('news-id').value = '';
        document.getElementById('news-title').value = '';
        document.getElementById('news-image').value = '';
        document.getElementById('news-content').value = '';
        document.getElementById('news-status').value = '';
        document.getElementById('news-modal').classList.remove('hidden');

        document.getElementById('btn-save').onclick = function () {
            if (document.getElementById('news-title').value === '' || document.getElementById('news-content').value === '' || document.getElementById('news-text').value === '' || document.querySelector('#news-type option:checked').value === '--选择分类--' || document.querySelector('#news-status option:checked').value === '') {
                alert("请填写完整信息！");
                return;
            }
            $.ajax({
                url: '/list/add/news',
                method: 'POST',
                contentType: 'application/json',
                headers: {
                    'X-Custom-Header': 'value'
                },
                data: JSON.stringify({
                    cover: document.querySelector('#news-image').value,
                    title: document.getElementById('news-title').value,
                    content: document.getElementById('news-content').value,
                    text: document.getElementById('news-text').value,
                    status: document.querySelector('#news-status option:checked').value,
                    category: document.querySelector('#news-type option:checked').value,
                    author: document.getElementById('news-author').value
                }),
                success: function () {
                    alert("成功！");
                    location.reload();
                },
                error: function () {
                    alert("出错了！");
                    location.reload();
                }
            });
        }
    }

    function closeModal() {
        document.getElementById('news-modal').classList.add('hidden');
    }

    function search() {
        var text = $("#news-search").val();
        var type = $("#type-select option:checked").val()
        $.ajax({
            url: '/list/search/news?title=' + text + '&category=' + type,
            method: 'GET',
            success: function (data) {
                var html = '';
                for (var i = 0; i < data.length; i++) {
                    html += '<tr><td>' + (parseInt(i + 1)) + '</td><td>' + data[i].title + '</td><td>'
                        + data[i].category + '</td><td>' + data[i].air_time + '</td><td>' + data[i].author + '</td><td>';
                    if (data[i].status === 1) {
                        html += '<span style="color: #2ecc71">已发布</span>';
                    } else {
                        html += '<span style="color:#f39c12">草稿</span>';
                    }
                    var id = data[i].id;
                    html += '</td><td><button class="edit-btn" onclick="openAddModal(\'' + id + '\')">编辑</button><button class="delete-btn" onclick="deleteNews(\'' + id + '\')">删除</button></td></tr>';
                }
                $("tbody").html(html);
            },
            error: function () {
                alert("出错了！");
            }
        });
    }
</script>
</body>